# _*_ coding: utf-8 _*_
# @Time:2023/11/28 9:25
# @Author:10917
# @File:user_manage_view.py
from django.shortcuts import render, redirect
from tw591 import models
from tw591.utils.formlist import UserInfoModelForm
from tw591.utils.pagination import Pagination


# 用户管理相关
def user_list(request):
    """ 用户管理 """

    # 获取所有用户列表 [obj,obj,obj]
    # queryset = models.UserInfo.objects.all()
    # return render(request, 'user_list.html', {"queryset": queryset})

    data_dict = {}
    search_data = request.GET.get('u_id', "")
    if search_data:
        data_dict["name__contains"] = search_data

    queryset = models.UserInfo.objects.filter(**data_dict)

    page_object = Pagination(request, queryset)

    context = {
        "search_data": search_data,

        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, 'user_list.html', context)


def user_add(request):
    if request.method == "GET":
        form = UserInfoModelForm()
        return render(request, "user_add.html", {"form": form})

    form = UserInfoModelForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user_list/")
    return render(request, "user_add.html", {"form": form})


def user_edit(request, uid):
    row_object = models.UserInfo.objects.filter(id=uid).first()
    if request.method == "GET":
        form = UserInfoModelForm(instance=row_object)
        return render(request, "user_edit.html", {"form": form})

    form = UserInfoModelForm(request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/user_list/")
    return render(request, "user_edit.html", {"form": form})


def user_delete(request, uid):
    models.UserInfo.objects.filter(id=uid).delete()
    return redirect("/user_list/")
